package com.qf.blog.controller;

import com.qf.blog.commons.constants.SysConsts;
import com.qf.blog.commons.response.ResponseResult;
import com.qf.blog.commons.security.UserTokenThreadLocal;
import com.qf.blog.commons.utils.CookieUtils;
import com.qf.blog.dto.FollowCount;
import com.qf.blog.entity.BlogPage;
import com.qf.blog.entity.PostPage;
import com.qf.blog.entity.User;
import com.qf.blog.service.FollowVoService;
import com.qf.blog.service.IPostService;
import com.qf.blog.service.IUserService;
import com.qf.blog.service.impl.UserTokenService;
import com.qf.blog.vo.LetterVo;
import com.qf.blog.vo.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author Zhendong Song
 * @date 2023/6/3
 * @description
 */
@Controller
@RequestMapping ("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IPostService postService;
    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private FollowVoService followVoService;

    /**
     * 登录
     *
     * @param user
     * @author ywl
     **/

    @PostMapping ("/login")
    @ResponseBody
    public ResponseResult login(@RequestBody User user, HttpServletResponse response) {
        UserToken userToken = userService.login(user);
        Cookie cookie = new Cookie(SysConsts.LOGIN_COOKIE_KEY, userToken.getUuid());
        cookie.setPath("/");
        cookie.setMaxAge(SysConsts.CookExpireTime.ONE_HOUR); // 设置过期时间
        response.addCookie(cookie);
        return ResponseResult.success();
    }

    /**
     * 退出登录
     *
     * @author Zhendong Song
     * @time 2023/6/8 14:16
     */

    @GetMapping ("/logout")
    @ResponseBody
    public ResponseResult logout() {
        userTokenService.remove();
        return ResponseResult.success();
    }

    /**
     * 注册
     *
     * @param user
     * @author Zhendong Song
     * @time 2023/6/8 14:16
     */
    @PostMapping ("/register")
    @ResponseBody
    public ResponseResult register(@RequestBody User user) {
        userService.register(user);
        return ResponseResult.success();
    }

    /**
     * 激活邮箱
     *
     * @param code
     * @author Zhendong Song
     * @time 2023/6/8 14:15
     */

    @GetMapping ("/activate/{code}")
    @ResponseBody
    public String register(@PathVariable String code) throws Exception {
        Boolean isOk = userService.activate(code);
        if (isOk) {
            return "site/login";
        }
        return "<a>激活失败 请检查您的激活链接</a>";
    }

    /**
     * 修改头像
     *
     * @param headerUrl
     * @author ywl
     * @time 2023/6/8 14:12
     */

    @PostMapping ("/update/avatar")
    @ResponseBody
    public ResponseResult update(@RequestBody String headerUrl) {
        userService.updateAvatar(headerUrl.replace("\"", ""));
        return ResponseResult.success();
    }

    /**
     * 修改密码
     *
     * @param data
     * @return com.qf.blog.commons.response.ResponseResult
     * @author Zhendong Song
     * @time 2023/6/8 14:13
     */

    @PostMapping ("/update/password")
    @ResponseBody
    public ResponseResult update(@RequestBody Map<String, String> data) {
        String oldPassword = data.get("oldPassword");
        String newPassword = data.get("newPassword");
        UserToken userToken = UserTokenThreadLocal.get();
        Integer userId = userToken.getUserId();
        userService.updatePwd(userId, oldPassword, newPassword);
        return ResponseResult.success();
    }

    /**
     * 个人主页查询
     *
     * @param userId
     * @param request
     * @author Zhendong Song
     * @time 2023/6/8 14:11
     */
    @GetMapping ("/profile/{userId}")
    public String getProfile(@PathVariable Integer userId, HttpServletRequest request) {
        User user = userService.getById(userId);
        request.setAttribute("user", user);
        boolean isFollow = followVoService.isFollow(userId);
        request.setAttribute("hasFollowed", isFollow);
        FollowCount followCount = followVoService.followCount(userId);
        request.setAttribute("followCount", followCount);
        return "site/profile";
    }

    /**
     * 我的帖子
     *
     * @author Zhendong Song
     * @time 2023/6/9 14:46
     */
    @GetMapping ("/post/query")
    public String queryPosts(PostPage page, Model model) {
        UserToken userToken = UserTokenThreadLocal.get();
        Integer userId = userToken.getUserId();
        page.setUserId(userId);
        page.setPath("/user/post/query");
        PostPage pospage = postService.queryPage(page);
        model.addAttribute("page", pospage);
        return "site/my-post";
    }

    /**
     * 消息
     *
     * @param model
     * @author Zhendong Song
     * @time 2023/6/12 16:23
     */
    @GetMapping ("/message/query")
    public String queryMessages(Model model) {
        List<LetterVo> letterVoList=userService.queryMessages();
        model.addAttribute("letterVoList",letterVoList);
        return "site/letter.html";
    }

    /**
     * 发起/取消关注
     *
     * @param userId 要关注的用户id
     * @param type   1发起关注 2取消关注
     * @author ywl
     * @time 2023/6/8 18:57
     */

    @GetMapping ("/follow/{userId}")
    @ResponseBody
    public ResponseResult follow(@PathVariable Integer userId, Integer type) {
        if (userId > 0 && type > 0) {
            followVoService.follow(userId, type);
        }
        return ResponseResult.success();
    }

    @PostMapping ("/resetPwd")
    public String resetPwd(User user) {
        String value = CookieUtils.getValue(SysConsts.VERIFY_CODE);
        userService.resetPwd(user, value);
        return "site/login";
    }

    @RequestMapping ("/email/send")
    @ResponseBody
    public ResponseResult sendEmail(@RequestBody User user) {
        userService.sendEmail(user);
        return ResponseResult.success();
    }

    @RequestMapping ("/email/verify/{code}")
    public String verifyEmail(@PathVariable String code, HttpServletResponse response) {
        String verifyCode = userService.verifyEmail(code);
        Cookie cookie = new Cookie(SysConsts.VERIFY_CODE, verifyCode);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "site/reset-pwd";
    }
}
